from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.executors.pool import ThreadPoolExecutor
from django.conf import settings
from functools import wraps
import pytz
from common.utils.logger import Logger

class TaskScheduler:
    """定时任务调度器"""
    _instance = None
    _scheduler = None
    _initialized = False

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        if not self._initialized:
            # 构建正确的数据库 URL
            db_url = (
                'postgresql://'  # 使用 postgresql:// 而不是 postgresql.postgresql://
                f"{settings.DATABASES['default']['USER']}:"
                f"{settings.DATABASES['default']['PASSWORD']}@"
                f"{settings.DATABASES['default']['HOST']}:"
                f"{settings.DATABASES['default']['PORT']}/"
                f"{settings.DATABASES['default']['NAME']}"
            )

            # 配置任务存储
            jobstores = {
                'default': SQLAlchemyJobStore(url=db_url)
            }

            # 配置执行器
            executors = {
                'default': ThreadPoolExecutor(20)
            }

            # 创建调度器
            self._scheduler = BackgroundScheduler(
                jobstores=jobstores,
                executors=executors,
                timezone=pytz.timezone(settings.TIME_ZONE)
            )
            self._initialized = True

    def start(self):
        """启动调度器"""
        if not self._scheduler.running:
            self._scheduler.start()
            Logger.info("Task scheduler started")

    def shutdown(self):
        """关闭调度器"""
        if self._scheduler.running:
            self._scheduler.shutdown()
            Logger.info("Task scheduler shutdown")

    def add_job(self, func, trigger, **trigger_args):
        """添加任务"""
        return self._scheduler.add_job(func, trigger, **trigger_args)

    def remove_job(self, job_id):
        """移除任务"""
        self._scheduler.remove_job(job_id)

    def get_job(self, job_id):
        """获取任务"""
        return self._scheduler.get_job(job_id)

    def get_jobs(self):
        """获取所有任务"""
        return self._scheduler.get_jobs()

    @classmethod
    def cron(cls, **kwargs):
        """Cron 装饰器"""
        def decorator(func):
            @wraps(func)
            def wrapper(*args, **kw):
                return func(*args, **kw)
            wrapper._is_scheduled = True
            wrapper._schedule_args = {
                'trigger': 'cron',
                **kwargs
            }
            return wrapper
        return decorator

    @classmethod
    def interval(cls, **kwargs):
        """间隔装饰器"""
        def decorator(func):
            @wraps(func)
            def wrapper(*args, **kw):
                return func(*args, **kw)
            wrapper._is_scheduled = True
            wrapper._schedule_args = {
                'trigger': 'interval',
                **kwargs
            }
            return wrapper
        return decorator

# 创建全局调度器实例
scheduler = TaskScheduler() 


# 使用方式

# 1.Cron 表达式
# @TaskScheduler.cron(hour=2, minute=30)
# def my_task():
#     pass

# 2.固定间隔
# @TaskScheduler.interval(hours=1)
# def another_task():
#     pass

#
# from common.core.scheduler import scheduler

# def my_job():
#     pass

# # 添加 cron 任务
# scheduler.add_job(my_job, 'cron', hour=2)

# # 添加间隔任务
# scheduler.add_job(my_job, 'interval', hours=1)